<template>
  <div class="goods-add">
    <!-- 1、面包屑导航  -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2.卡片 -->
    <el-card>
      <!-- 2-1、alert 警告调 -->
      <el-alert
        title="只能添加三级分类的商品信息"
        type="info"
        show-icon
        :closable="false"
        center
      />
      <!-- 2-2、步骤条 -->
      <el-steps :active="active - 1">
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品描述" />
        <el-step title="完成" />
      </el-steps>
      <!-- 2-3、Tabs 标签页 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="80px"
        size="large"
      >
        <el-tabs
          tab-position="left"
          style="min-height: 200px"
          class="demo-tabs"
          v-model="active"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" :name="1">
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                style="width: 100% !important"
                v-model="addForm.goods_cat"
                placeholder="请选择商品分类"
                :options="cateList"
                :props="props"
                clearable
              />
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" clearable />
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" clearable />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" clearable />
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" clearable />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" :name="2">
            <el-row
              v-for="item in manyAttrList"
              :key="item.attr_id"
              class="many-row"
            >
              <el-col :span="2">{{ item.attr_name }}</el-col>
              <el-col :span="22">
                <el-checkbox-group v-model="item.attr_vals" size="default">
                  <el-checkbox
                    :label="item1"
                    border
                    v-for="item1 in item.attr_vals"
                    :key="item1"
                  />
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品属性" :name="3">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyAttrList"
              :key="item.attr_id"
              label-width="150px"
            >
              <el-input v-model="item.attr_vals" clearable />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" :name="4">
            <!-- 使用缩略图文件上传组件 -->
            <el-upload
              class="upload-demo"
              :action="$imgUrl + 'upload'"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :multiple="true"
              :file-list="fileList"
              list-type="picture-card"
              :headers="{ Authorization }"
            >
              <el-button type="primary" :icon="Upload">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">jpg/png 文件尺寸小于500kb</div>
              </template>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品描述" :name="5">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                mode="default"
              />
              <Editor
                style="height: 350px; overflow-y: hidden"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="handleCreated"
              />
            </div>
            <el-button type="primary" @click="submitAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 3、预览图片对话框 -->
    <el-dialog title="图片预览" v-model="previewDialogVisible" width="50%">
      <img w-full :src="previewUrl" alt="Preview Image" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script setup>
/*---------------------- 引入资源 ---------------------- */
import {
  ref,
  reactive,
  onMounted,
  computed,
  onBeforeUnmount,
  shallowRef,
  getCurrentInstance,
} from "vue";
import { ArrowRight, Upload } from "@element-plus/icons-vue";
import { error, success } from "@/utils/message";
import request from "@/utils/request";
// 引入wangge的副文本编辑器
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { useRouter } from "vue-router";
/*---------------------- 定义变量 ---------------------- */
let { $imgUrl } = getCurrentInstance().appContext.config.globalProperties,
  router = useRouter(),
  Authorization = computed(() => {
    let str = sessionStorage.getItem("user-login");
    if (!str) {
      return "token";
    }
    return JSON.parse(str).data.token;
  }), // 获取token
  active = ref(1),
  addFormRef = ref(),
  addForm = reactive({
    goods_name: "",
    goods_cat: [],
    goods_price: 1,
    goods_number: 1,
    goods_weight: 1,
    goods_introduce: "",
  }),
  cateList = ref([]),
  goodsCatL3 = computed(() => {
    let arr = addForm.goods_cat; //[1,6,9]
    return arr.length ? arr[2] : 0;
  }), // 通过计算属性获得三级分类的id
  rules = ref({
    goods_cat: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
    goods_name: [
      { required: true, message: "请输入商品名称", trigger: "blur" },
      { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" },
    ],
    goods_price: [
      { required: true, message: "请输入商品价格", trigger: "blur" },
      {
        validator: (reg, value, cb) => {
          reg = /^\d+(\.\d+)?$/;
          if (!reg.test(value)) {
            return cb(new Error("商品价格必须是正数"));
          }
          cb();
        },
        trigger: "blur",
      },
    ],
    goods_number: [
      { required: true, message: "请输入商品数量", trigger: "blur" },
      {
        validator: (reg, value, cb) => {
          reg = /^\d+(\.\d+)?$/;
          if (!reg.test(value)) {
            return cb(new Error("商品数量必须是正数"));
          }
          cb();
        },
        trigger: "blur",
      },
    ],
    goods_weight: [
      { required: true, message: "请输入商品重量", trigger: "blur" },
      {
        validator: (reg, value, cb) => {
          reg = /^\d+(\.\d+)?$/;
          if (!reg.test(value)) {
            return cb(new Error("商品重量必须是正数"));
          }
          cb();
        },
        trigger: "blur",
      },
    ],
  }),
  manyAttrList = ref([]), //动态参数
  onlyAttrList = ref([]), //静态参数
  pics = ref([]), //保存图片路径的数组
  fileList = ref([]), //上传文件的列表
  previewUrl = ref(""), //预览图片的url
  previewDialogVisible = ref(false); //控制预览图片的弹窗
// 商品分类列表
const props = {
  expandTrigger: "hover",
  value: "cat_id",
  label: "cat_name",
  children: "children",
};
//--------------------wangge editor
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  autoFocus: true,
};
// 只能使用shallowRef
const editorRef = shallowRef();
const valueHtml = ref("<p>hello</p>");
//--------------------wangge editor
/*---------------------- 功能函数 ---------------------- */
async function addGoods() {
  let attrs = [];
  // 动态参数
  for (let item of manyAttrList.value) {
    let attr_vals = item.attr_vals ?? [];
    attrs.push({ attr_id: item.attr_id, attr_value: attr_vals.join(",") });
  }
  // 静态参数
  for (let item of onlyAttrList.value) {
    attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals });
  }
  let option = {
    url: "goods",
    type: "post",
    data: {
      goods_name: addForm.goods_name,
      goods_cat: addForm.goods_cat.join(","),
      goods_price: addForm.goods_price,
      goods_number: addForm.goods_number,
      goods_weight: addForm.goods_weight,
      goods_introduce: valueHtml.value,
      pics: pics.value,
      attrs,
    },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 201) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    router.push("/goods");
  } catch (error) {
    console.log(error);
  }
}
function submitAdd() {
  let form = addFormRef.value;
  form.validate((v) => {
    if (!v) {
      return error("请正确填写商品信息");
    }
    addGoods();
  });
}
//上传之前验证图片类型
function beforeUpload(file) {
  if (!file) {
    error("请上传图片类型的文件");
    return false;
  }
  let { size, type } = file;
  // 判断是否是/+图片类型结尾
  let reg = /\/(jpg|png|jpeg|gif|bmp|webp|ico)$/;
  if (!reg.test(type)) {
    error("请上传图片类型的文件");
    return false;
  }
  if (size > 500 * 1024) {
    error("文件大小不能超500KB");
    return false;
  }
  return true;
}
// 预览图片执行从操作
function handlePreview(uploadFile) {
  previewUrl.value = uploadFile.response.data.url;
  previewDialogVisible.value = true;
}
// 删除图片执行的操作
function handleRemove(uploadFile) {
  let tmp_path = uploadFile.response.data.tmp_path, //获得要删除的图片的路径
    arr = pics.value,
    index = arr.findIndex((item) => item.tmp_path === tmp_path);
  arr.splice(index, 1);
  success("删除成功");
}
// 上传成功时执行的回调函数
function handleSuccess(res) {
  console.log(res);
  if (res.meta.status !== 200) {
    return error(res.meta.msg);
  }
  success(res.meta.msg);
  pics.value.push({ pic: res.data.tmp_path });
}
// 获得当前三级分类的动态参数
async function getOnlyAttr() {
  let option = {
    url: `categories/${goodsCatL3.value}/attributes`,
    type: "get",
    data: { sel: "only" },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    let arr = res.data;
    console.log(arr, "arr");
    onlyAttrList.value = arr;
  } catch (error) {
    console.log(error);
  }
}
//获取当前三级分类的动态参数
async function getManyAttr() {
  let option = {
    url: `categories/${goodsCatL3.value}/attributes`,
    type: "get",
    data: { sel: "many" },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    let arr = res.data;
    for (const iterator of arr) {
      let attr_vals = JSON.parse(JSON.stringify(iterator.attr_vals));
      if (!attr_vals) {
        iterator.attr_vals = [];
      } else {
        iterator.attr_vals = attr_vals.split(",");
      }
    }
    manyAttrList.value = arr;
  } catch (error) {
    console.log(error);
  }
}
//请求所有商品分类数据
async function getCategories() {
  let option = {
    url: "categories",
    type: "get",
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    cateList.value = res.data;
  } catch (error) {
    console.log(error);
  }
}
//tabs标签页跳转时的拦截操作 return false无法跳转
function beforeLeave(activeName) {
  if (activeName !== 1) {
    if (addForm.goods_cat.length === 0) {
      error("请选择商品分类");
      return false;
    }
    //点击的是商品参数 tab
    if (activeName === 2) {
      getManyAttr();
    }
    if (activeName === 3) {
      getOnlyAttr();
    }
  }
  return true;
}
/*---------------------- 周期函数 ---------------------- */
onMounted(() => {
  handleCreated();
  getCategories();
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor === null) return;
  editor.destroy();
});
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style lang="scss" scoped>
.el-card {
  margin: 10px 0;
}
.el-steps {
  padding: 15px 0;
  :deep(.el-step__title) {
    font-size: 14px;
  }
}

.el-alert {
  background-color: #0095ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  :deep(.el-alert__content) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &:hover {
    background-color: #0065ff;
    cursor: pointer;
  }
}
.many-row {
  font-size: 14px;
  .el-col {
    padding: 10px 0;
    .el-checkbox {
      margin-right: 10px;
    }
  }
}
.previewImg {
  width: 100%;
}
#content {
  width: 100%;
  display: block;
  word-break: break-all;
  word-wrap: break-word;
}
</style>